import Taro from "@tarojs/taro";

const BASE_URL = {
  COORDINATE_CONVERT:
    "https://restapi.amap.com/v3/assistant/coordinate/convert", // 基础坐标转换
  IP_ADDRESS: "https://restapi.amap.com/v5/ip/location", // ip转地址
  IP_ADDRESS_BASE: "https://restapi.amap.com/v3/ip", // ip转地址
};

const API_KEY = process.env.VUE_APP_PLATFORM == 'release' ? "1940f6076c4826a71ec26b5392567de6" : "33faf322b3e7950244722471cd7370a9"; // AMAP APIKEY

export const getLocation = () => {
  return new Promise((resolve, reject) => {
    Taro.getLocation({
      type: "wgs84",
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        console.log('获取位置失败：', err);
        reject(err);
      },
    });
  });
};

export const getAddressFromMap = () => {
  return new Promise(async (resolve, reject) => {
    const { latitude, longitude } = await getLocation();

    Taro.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success: function (res) {
        return resolve(res)
      },
      fail: (err) => {
        console.log("🚀 ~ getAddressFromMap ~ err:", err)
        reject(err);
      },
    });
  })
}

const location2Address = () => {
  return new Promise(async (resolve, reject) => {
    const { latitude, longitude } = await getLocation();
    console.log("data:==========>", { latitude, longitude });

    if (!latitude || !longitude) {
      return reject("获取位置失败");
    }

    Taro.request({
      url: BASE_URL.COORDINATE_CONVERT,
      data: {
        key: API_KEY,
        locations: `${longitude},${latitude}`,
        coordsys: "gps",
      },
      success: (res) => {
        console.log("🚀 ~ returnnewPromise ~ res:", res);
      },
    });
  });
};

const ip2Address = () => {
  console.log('API_KEY:', API_KEY);
  return new Promise(async (resolve, reject) => {
    Taro.request({
      url: BASE_URL.IP_ADDRESS_BASE,
      data: {
        key: API_KEY,
      },
      success: (res) => {
        console.log("🚀 ~ ip2Address ~ res:", res)
        const { status, city, province, info } = res.data;

        if (status !== '1') {
          return resolve({ err: -1, msg: info });
        }

        return resolve({ err: 0, address: `${province} ${city}` })
      },
    });
  });
}

export { location2Address, ip2Address };
